/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.common.utils.codec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 */
public class MD5Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(MD5Utils.class);

    private static final String UTF8 = "UTF-8";

    private static final String ALGORITHM_NAME = "MD5";

    private static byte[] md5(String src) {
        MessageDigest algorithm;
        try {
            algorithm = MessageDigest.getInstance(ALGORITHM_NAME);
            algorithm.reset();
            algorithm.update(src.getBytes(UTF8));
            return algorithm.digest();
        } catch (Exception e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("MD5 Error, {}", e);
            }
        }
        return null;
    }

    public static String md5Digest(String src) {
        // 定义数字签名方法, 可用：MD5, SHA-1
        try {
            MessageDigest md = MessageDigest.getInstance(ALGORITHM_NAME);
            byte[] bytes = md.digest(src.getBytes(UTF8));
            return byte2HexStr(bytes);
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 字节数组转化为大写16进制字符串
     *
     * @param bytes 字节数组
     * @return 大写十六进制字符串
     */
    private static String byte2HexStr(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            String s = Integer.toHexString(aByte & 0xFF);
            if (s.length() == 1) {
                sb.append("0");
            }
            sb.append(s.toUpperCase());
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String name = "Charkey";
        System.out.println(MD5Utils.md5Digest(name));
        System.out.println(byte2HexStr(MD5Utils.md5(name)));
    }
}